#include "dictdatadlg.h"
#include "editdictdatadlg.h"
#include "ui_dictdatadlg.h"

DictDataDlg::DictDataDlg(qlonglong id,QList<DictData> statusList,
                         QString dictType,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DictDataDlg)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/image/res/stm.jpg"));
    setWindowTitle("编辑字典数据");
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_hideSearch->setIcon(pix);
    ui->btn_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_refresh->setIcon(freshPix.scaled(25,25));
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

    this->dictId = id;
    this->statusList = statusList;
    this->type = dictType;

    init();
}

DictDataDlg::~DictDataDlg()
{
    delete ui;
}

void DictDataDlg::init()
{
    getOptionList();
    getDictType();
    initSearchArea();
    getList();
    initTable();
    initPageInfo();
}

void DictDataDlg::getOptionList()
{
    optionList.clear();
    QByteArray *data = api.getOptionList();
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    if(obj.value("code").toInt() != 200) return;
    QJsonArray arr = obj.value("data").toArray();
    for(int i = 0;i< arr.size();i++){
        optionList.append(DictType::toDictType(arr.at(i).toObject()));
    }
}

void DictDataDlg::getDictType()
{
    QByteArray *data = api.getById(this->dictId);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    if(obj.value("code").toInt() != 200) return;
    dictType = DictType::toDictType(obj.value("data").toObject());
}

void DictDataDlg::getList()
{
    dictDataList.clear();
    QString dictType = ui->comboBox_dictName->itemData(ui->comboBox_dictName->currentIndex()).value<QString>();
    QString status = ui->comboBox_status->itemData(ui->comboBox_status->currentIndex()).value<QString>();
    QString dictLabel = ui->lineEdit_dictLabel->text();
    QByteArray *data = api.getDictDataList(currentPage,pageSize,dictType,status,dictLabel);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    if(obj.value("code").toInt() != 200) return;
    total = obj.value("total").toInt();
    QJsonArray arr = obj.value("rows").toArray();
    for(int i = 0;i< arr.size();i++){
        dictDataList.append(DictData::toDictData(arr.at(i).toObject()));
    }
}

void DictDataDlg::initSearchArea()
{
    ui->comboBox_dictName->clear();
    ui->comboBox_status->clear();
    for(int i = 0;i< optionList.size();i++){
        ui->comboBox_dictName->addItem(optionList.at(i).dictName,optionList.at(i).dictType);
        if(optionList.at(i).dictType == type){
            ui->comboBox_dictName->setCurrentIndex(i);
        }
    }
    ui->comboBox_status->addItem("");
    for(int i = 0;i< statusList.size();i++){
        ui->comboBox_status->addItem(statusList.at(i).dictLabel,statusList.at(i).dictValue);
    }
}

void DictDataDlg::initTable()
{
    ui->tableWidget->setSortingEnabled(0);
    ui->tableWidget->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget->clear();
    QStringList columnHeader;
    columnHeader << "字典编号" << "字典标签" << "字典键值" << "字典排序" << "状态" << "备注" << "创建时间" << "操作";
    ui->tableWidget->setColumnCount(columnHeader.size());
    ui->tableWidget->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget->setRowCount(dictDataList.size());
    ui->tableWidget->setColumnWidth(7,165);
    for(int i = 0;i< dictDataList.size();i++){
        ui->tableWidget->setRowHeight(i,38);
        QString dictCode = QString::number(dictDataList.at(i).dictCode);
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(dictCode));

        QLabel *dictLabel = new QLabel();
        dictLabel->setText(dictDataList.at(i).dictLabel);
        dictLabel->setAlignment(Qt::AlignCenter);
        dictLabel->setStyleSheet(utils.backShowStyle[dictDataList.at(i).listClass]);
        QSize size = dictLabel->sizeHint();
        // 将大小应用于 QLabel
        dictLabel->setFixedSize(size.width() + 20,size.height() + 10);
        QWidget *widgetType = new QWidget();
        QHBoxLayout* hLayoutType = new QHBoxLayout(widgetType);
        dictLabel->setAlignment(Qt::AlignCenter);
        hLayoutType->addWidget(dictLabel);
        ui->tableWidget->setCellWidget(i,1,widgetType);

        ui->tableWidget->setItem(i,2,new QTableWidgetItem(dictDataList.at(i).dictValue));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(QString::number(dictDataList.at(i).dictSort)));

        QLabel *statusLabel = new QLabel();
        for (int j = 0; j < statusList.size(); ++j) {
            if(dictDataList.at(i).status == statusList.at(j).dictValue){
                statusLabel->setText(statusList.at(j).dictLabel);
                statusLabel->setStyleSheet(utils.backShowStyle[statusList.at(j).listClass]);
                break;
            }
        }
        statusLabel->setFixedSize(46,20);
        statusLabel->setAlignment(Qt::AlignCenter);
        QWidget *widget = new QWidget();
        QHBoxLayout* hLayout = new QHBoxLayout(widget);
        statusLabel->setAlignment(Qt::AlignCenter);
        hLayout->addWidget(statusLabel);
        ui->tableWidget->setCellWidget(i,4,widget);

        ui->tableWidget->setItem(i,5,new QTableWidgetItem(dictDataList.at(i).remark));
        ui->tableWidget->setItem(i,6,new QTableWidgetItem(dictDataList.at(i).createTime));

        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnUpdate = new QPushButton;
        QPushButton *btnDelete = new QPushButton;
        connect(btnDelete,&QPushButton::clicked,this,[=](){
            int flag  = QMessageBox::question(0,"提示","确定删除该项吗?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                if(flag == QMessageBox::No) return;
                QByteArray *bytes = api.deleteDictDataItems(dictCode);
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                if(200 == obj.value("code").toInt()){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    getList();
                    initTable();
                    initPageInfo();
                }
            }
        });
        connect(btnUpdate,&QPushButton::clicked,this,[=](){;
            EditDictDataDlg *e = new EditDictDataDlg(dictDataList.at(i).dictCode);
            e->setAttribute(Qt::WA_DeleteOnClose);
            connect(e,&EditDictDataDlg::success,this,[=](){
                getList();
                initTable();
                initPageInfo();
            });
            e->exec();
        });
        btnDelete->setText("🗑删除");
        btnDelete->setFixedSize(80,35);
        btnUpdate->setText("🖍修改");
        btnUpdate->setFixedSize(80,35);
        btnUpdate->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(231, 250, 240);color: black;}QPushButton:hover {background-color: rgb(19, 206, 102);}QPushButton:pressed {background-color: rgb(19, 150, 102);}");
        btnDelete->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
        tmp_layout->addWidget(btnUpdate);
        tmp_layout->addWidget(btnDelete);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget->setCellWidget(i,7,tmp_widget);
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget->setSortingEnabled(1);
}

void DictDataDlg::initPageInfo()
{
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_count->setText("共"+QString::number(total)+"条");
    if(currentPage == 1){
        ui->btn_pervious->setEnabled(0);
    }else{
        ui->btn_pervious->setEnabled(1);
    }
    ui->label_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_next->setEnabled(0);
    }else{
        ui->btn_next->setEnabled(1);
    }
}

void DictDataDlg::on_btn_close_clicked()
{
    this->close();
}

void DictDataDlg::on_comboBox_pageItem_currentIndexChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTable();
    initPageInfo();
}


void DictDataDlg::on_btn_pervious_clicked()
{
    ui->btn_pervious->setEnabled(0);
    currentPage--;
    init();
    ui->btn_pervious->setEnabled(1);
    initPageInfo();
}


void DictDataDlg::on_btn_next_clicked()
{
    ui->btn_next->setEnabled(0);
    currentPage++;
    init();
    ui->btn_next->setEnabled(1);
    initPageInfo();
}

void DictDataDlg::on_btn_hideSearch_clicked()
{
    ui->widget_2->setHidden(!ui->widget_2->isHidden());
}


void DictDataDlg::on_btn_refresh_clicked()
{
    getList();
    initTable();
    initPageInfo();
}


void DictDataDlg::on_btn_search_clicked()
{
    getList();
    initTable();
    initPageInfo();
}


void DictDataDlg::on_btn_reset_clicked()
{
    ui->lineEdit_dictLabel->clear();
    ui->comboBox_status->setCurrentIndex(0);
    init();
}


void DictDataDlg::on_lineEdit_gotoPage_returnPressed()
{
    int page = ui->lineEdit_gotoPage->text().toInt();
    ui->lineEdit_gotoPage->clear();
    if(page < 1 || page > totalPage){
        ui->lineEdit_gotoPage->setStyleSheet("border:1px solid red;");
        return;
    }
    ui->lineEdit_gotoPage->setStyleSheet("");
    currentPage = page;
    getList();
    initTable();
    initPageInfo();
}


void DictDataDlg::on_btn_add_clicked()
{
    EditDictDataDlg *e = new EditDictDataDlg(-1,type);
    e->setAttribute(Qt::WA_DeleteOnClose);
    connect(e,&EditDictDataDlg::success,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    e->exec();
}


void DictDataDlg::on_btn_del_clicked()
{
    QList<QTableWidgetItem*> items = ui->tableWidget->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 5;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget->row(items.at(i * 5));
        if(i != rowCount - 1){
            ids += ui->tableWidget->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选项吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = api.deleteDictDataItems(ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTable();
        initPageInfo();
    }
}


void DictDataDlg::on_btn_update_clicked()
{
    int index = ui->tableWidget->currentRow();
    if(index < 0) return;
    QString id = ui->tableWidget->item(index,0)->text();
    EditDictDataDlg e(id.toLong());
    connect(&e,&EditDictDataDlg::success,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    e.exec();
}


void DictDataDlg::on_btn_export_clicked()
{
    utils.exportExcel(ui->tableWidget,"字典数据表格");
}

